package com.da.javatest.thread.juc.aqs;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import lombok.Data;

/**
 * @author chenlida
 * @date 2020/9/6 15:56
 * @description
 */
@Data
public class MyLockTest {
    private int stock = 5;
    private MyLock myLock = new MyLock();

    public static void main(String[] args) {
        MyLockTest test = new MyLockTest();
        ExecutorService es = Executors.newFixedThreadPool(10);
        // 模拟访问
        for (int i = 0; i < 5; i++) {
            es.execute(() -> {
                for (int j = 0; j < 10; j++) {
                    System.out.println(test.seller());
                }
            });
        }

        es.shutdown();
    }

    /**
     * 模拟售卖
     */
    private String seller() {
        myLock.lock();
        int stock = getStock();
        if (stock <= 0) {
            myLock.unlock();
            return "下单失败。没有库存了！";
        }

        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stock--;
        setStock(stock);

        myLock.unlock();
        return Thread.currentThread().getName() + "下单成功，剩余库存为：" + stock;
    }
}
